package com.JL.engine.View;

import com.JL.engine.components.PositionComponent;
import com.JL.engine.model.Entity;
import com.JL.engine.model.View;
import com.JL.engine.util.LocalTimeUtil;


import java.awt.*;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class AnimationView implements View {
    private PositionComponent offset = new PositionComponent();
    private List<ImageView> images = new ArrayList<>();
    private LocalTimeUtil timeUtil = new LocalTimeUtil();
    private  int index = 0;
    private  int interval = 1000/21;
    private  int zindex;

    private int cycleCount;
    private boolean playState;

    public AnimationView(int zindex,List<ImageView> images){
        this.zindex = zindex;
        this.images.addAll(images);
    }
    public AnimationView(int zindex,ImageView...imageViews){
        this.zindex = zindex;
        this.images.addAll(Arrays.asList(imageViews));
    }
    @Override
    public Point2D getOffset(){
        return offset.getPosition();
    }

    public int getZindex(){return zindex;}
    public  int getInterval(){
        return  interval;
    }

    public int getCycleCount(){return cycleCount;}
    public  void setCycleCount(int cycleCount){
        this.cycleCount = cycleCount;
    }

    public  void setInterval(int interval){
        this.interval = interval;
    }
    public void play(){
        playState=true;
        this.cycleCount=1;
    }
    public void loop(int cycleCount){
        this.cycleCount=cycleCount;
        this.playState=true;
    }
    public void loop(){
        this.loop(-1);
    }
    public void stop(){
        this.playState=false;
        this.cycleCount=0;
    }
    @Override
    public  void draw(Graphics g, Entity entity){
        ImageView imageView = images.get(index);
        imageView.setPosition(offset.getPosition());
        imageView.draw(g,entity);
        if (playState){
            if(timeUtil.timeConsum(interval)&&(cycleCount>0 || cycleCount==-1)) {
                index++;
                if (index == images.size()) {
                    index = 0;
                    if (cycleCount>0){
                        cycleCount--;
                    }
                }
                timeUtil.reset();
            }
        }
    }
}